#include "ranking.h"
#include "video-graphics.h"
#include "video-text.h"

void init_score{
	Score.name = (char*) malloc (10*sizeof(char*));
	Score.score = 0;
}

Byte atributo = 0x0A;

struct Score* get_best_scores(char* filename)
{
	struct Score best_scores[10];
	struct Score temp_score;

	FILE *fp;
	fp=fopen(filename, "r+");
	int i = 0;
		while(!feof(fp))
		{
			int n;
			fscanf(fp, "%d", &n);
			temp_score.score = n;
			
			char* name = (char*) malloc (10*sizeof(char*));
			fscanf(fp, "%s", name);
			temp_score.name = name;
			
			best_scores.[i] = temp_score; 
			i++;
		}
		
		fclose(fp);
	return best_scores;
}

// visualiza as melhores pontuacoes
void show_best_scores(struct Score *bs)
{
	//Score[] * best_scores = &bs;
	
	printStringAt("Melhores pontuacoes ate' ao momento:", 10, 5, atributo); 
	int i;
	for (i = 0; i < bs.length; ++i)
	{
		char* buf = (char*) malloc (10*sizeof(char*));
		itoa(bs[i].score, buf, 10);
		char* sco = strcat(buf, " - ");
		sco = strcat(sco, best_scores[i].name); //verificar se existe concatencao de strings
		printStringAt(sco, 10, 10+ 5*(i), atributo);
	}
}

/// acrescenta um novo elemento ao array 'best_scores' na posicao certa
void update_best_scores(Score * best_scores, Score s)
{
	int i = 0;
	int a = 0;
	for(i; i < 10; i++) //ciclo que procura a posicao no array onde vai entrar o score
	{
		if(s.score >= best_scores[i])
		{
			a= i; 
		}
	}
	
	i = 10;
	
	for(i; i >= a; i--)
	{
		if(i==a)
		{
			best_scores[i].score = s.score;
			best_scores[i].score = s.name;
		}
		else
		{
			best_scores[i].score = best_scores[i-1].score;
			best_scores[i].name = best_scores[i-1].name;
		}
	}

}

// grava o conteudo do vector com as melhores pontuacoes
// num ficheiro
void save_best_scores(char* filename, Score * vs, int n_best)
{
	FILE *fp;
	fp=fopen(filename, "r+");
	int i;
	for (i = 0; i < 10; ++i)
	{
		fprintf(fp, "%d", vs[i].score);
		fprintf(fp, "%s", vs[i].name);
	}
	fclose(fp);
}

// visualiza a pontuacao final, actualiza as melhores pontuacoes
// e visualiza a lista das melhores pontuacoes
void game_over(int total_score, Score * best_scores)
{
	Byte atributos = 0x02; 
	char* a = "Pontuacao Final: ";
	PrintStringAt(a, 10, 15, atributo); //verificar posicoes x e y
	PrintIntAt(total_score, 15, 30, atributo);
	if((best_scores.length< 10) || (best_scores[9].score < total_score))
	{
		Score temp_score;
		temp_score.score = total_score;
		cls(' ', atributos); 
		PrintStringAt("Acabou de entrar para o ranking!", 25, 25, atributo);
		cls(' ', atributos);
		PrintStringAt("Nome? ", 10, 25, atributo);
		cls(' ', atributos);
		char* nome = (char*) malloc (10*sizeof(char*));
		scanf("%s", nome);
		temp_score.name = nome;
		update_best_scores(best_scores, temp_score);
		save_best_scores("Pontuacao.txt", best_scores, 10);
	}
	show_best_scores(best_scores);
}

